#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include "tedi2html.h"
#include "preprocessor.h"
#include "exception.h"
using namespace std;
/*
 * Check if entered file has:
 *   - !head and !end tags
 *   - Every "__"(list tag) has a ",," (end list tag)
 * Returns true if it's a valid tedi file.
 */
bool test_file(string file){
	stringstream inicio(file);
	string line;
	bool header=false;
	bool end=false;
	int start_list=0;
	int end_list=0;
	while(getline(inicio,line)){
		if(line[0]!='<'){
			size_t ul=line.find("__");
			if(ul!=string::npos)
				++start_list;
			size_t ulf=line.find(",,");
			if(ulf!=string::npos)
				++end_list;
		}
	}
	bool result=true;
	return result;
}
/*
 *  Load every file from '+' tag.
 */
string one_file(string file){
	string line;
	string text;
	ifstream reader(file);
	size_t slash=file.rfind("/");
	if(!reader)
		throw Invalid("File not loaded. Maybe file doesn't exist ",file);
	while(getline(reader,line)){
		if(line[0]!='+')
			text+=line + "\n";
		else{
			line=line.erase(0,1);

			if(slash!=string::npos)
				line=file.substr(0,slash+1)+line;

			ifstream include(line);
			string include_line;
			if(!include)
				throw Invalid("File not loaded. Maybe file doesn't exist ",line);
			while(getline(include,include_line))
				text+=include_line +"\n";
			
			include.close();
		}
	}
	reader.close();
	return text;
}
